<template>
  <Dialog v-model="dialogVisible" title="复制文件" width="450" @close="dialogVisible = false">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      class="form-wrap"
      label-width="120px"
    >
      <el-form-item label="目标文件组" prop="pid">
        <el-cascader
          style="max-width: 400px; width: 100%"
          v-model="formData.pid"
          clearable
          placeholder="请选择目标文件组"
          :options="treeGroupData"
          :props="cascaderProps"
          filterable
          :filter-method="sysFilterMethod"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { sysFilterMethod } from '@/utils/selectFilter'
import { getFileGroupTree, createFileManage } from '@/api/develop/file'

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const message = useMessage() // 消息弹窗
const currentRow = ref({})
const open = (row) => {
  formData.value.pid = ''
  dialogVisible.value = true
  currentRow.value = cloneDeep(row)
  console.log(currentRow.value, 'currentRow.value')
}
const treeGroupData = ref([])
const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false,
  disabled: (item) => {
    return item.id == currentRow.value.pid
  }
})

const formData = ref({ pid: '' })

const treeGroupDisable = computed(() => {
  return !!currentRow.value.pid
})
const formRules = reactive({
  pid: [{ required: true, message: '请选择目标文件组', trigger: ['blur', 'change'] }]
})
const formRef = ref<FormInstance>() // 表单 Ref

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

function reFreshTreeData() {
  getFileGroupTree({}).then((res) => {
    treeGroupData.value = res
  })
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value?.validate()
  if (!valid) {
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const params_ = {
      fileInfos: [{ ...currentRow.value, url: currentRow.value.path }],
      pid: formData.value.pid
    }

    await createFileManage(params_)
    message.success('复制成功')
    closeDialog()
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/** 重置表单 */

function closeDialog() {
  dialogVisible.value = false
}

onMounted(() => {
  reFreshTreeData()
})
</script>
<style lang="scss" scoped></style>
